<template>
  <div class="common-layout">
    <ElContainer>
      <ElHeader>
        <div class="header-left">
          <img src="../assets/image/container/logo.png" alt="" height="30" />
          <div class="title">AIGC照片名片</div>
        </div>
        <div class="header-right">
          <img src="../assets/image/container/icon_user.png" alt="" height="14" />
          <ElDropdown>
            <span class="el-dropdown-link">
              {{ userName }}
              <ElIcon class="el-icon--right">
                <arrow-down />
              </ElIcon>
            </span>
            <template #dropdown>
              <ElDropdownMenu>
                <!-- <ElDropdownItem @click="openDialog">修改密码</ElDropdownItem> -->
                <ElDropdownItem @click="setOut">退出登录</ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </div>
      </ElHeader>
      <ElContainer>
        <ElAside width="200px">
          <Menu :menuList="menuList"></Menu>
        </ElAside>
        <ElMain>
          <div class="main-btn">
            <TopBar />
          </div>
          <div class="main">
            <RouterView :key="router.currentRoute.value.path" v-if="judgeRouterView" />
            <el-empty v-else description="暂无该页面访问权限，请联系管理员或重新登录" />
          </div>
        </ElMain>
      </ElContainer>
    </ElContainer>

    <ElDialog v-model="dialogFormVisible" title="修改密码" width="600px">
      <!-- 新建编辑 -->
      <ElForm :model="form" :rules="formRules" ref="ruleFormRef">
        <ElFormItem label="旧密码" prop="old" labelWidth="100">
          <ElInput type="password" v-model="form.old" autocomplete="off"></ElInput>
        </ElFormItem>
        <ElFormItem label="新密码" prop="password" labelWidth="100">
          <ElInput type="password" v-model="form.password" autocomplete="off"></ElInput>
        </ElFormItem>
        <ElFormItem label="确认新密码" prop="passwordConfirm" labelWidth="100">
          <ElInput type="password" v-model="form.passwordConfirm" autocomplete="off"></ElInput>
        </ElFormItem>
        <ElFormItem label="验证码" prop="picCode" labelWidth="100">
          <ElInput v-model="form.picCode" autocomplete="off" maxlength="6">
            <template #append>
              <img class="verify-code" :src="imgVerifyCode" alt="验证码" @click="getVerifyCode" />
            </template>
          </ElInput>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="dialogFormVisible = false">取消</ElButton>
          <ElButton type="primary" @click="submit()"> 提交 </ElButton>
        </span>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import MenuService from '@/api/service/MenuService'
import AuthService from '@/api/service/AuthService'
import legalityCheck from '@/utils/LegalityCheck'
import Menu from './components/Menu.vue'
import TopBar from './components/TopBar.vue'
import FuncCrypt from '@/utils/FuncCrypt'
import useGlobalStore from '@/store/modules/global'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
// 全局缓存
const globalStore = useGlobalStore()
// RouterView判断权限是否存在
const judgeRouterView = computed(() => {
  let res = true
  const routerMeta = router.currentRoute.value.meta
  if (routerMeta.requiredAuth) {
    if (!globalStore.permissions.includes(routerMeta?.authKey as string)) {
      res = false
    }
  } else {
    res = true
  }
  return res
})

// 全局缓存
const userName = ref(globalStore?.userInfo?.realName)
const menuList = ref([])
// 修改密码弹框
const dialogFormVisible = ref(false)
const form = ref({
  old: '',
  password: '',
  passwordConfirm: '',
  picCode: '',
  picToken: ''
})
const imgVerifyCode = ref('')
// 公钥
const pubKey = ref('')

// 检查密码统一性
const checkPassWordSame = (rule: any, value: any, callback: any) => {
  if (value != form.value.password) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}
const formRules = {
  old: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  picCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
  password: legalityCheck.password,
  passwordConfirm: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { validator: checkPassWordSame, trigger: 'blur' }
  ]
}
// 获取公钥
const getPubKey = () => {
  AuthService.getPubKey().then((res: any) => {
    pubKey.value = res.result
  })
}
// 提交修改密码
const submit = () => {
  let params = Object.assign(form.value)
  params.password = FuncCrypt.rsaEncrypt(params.password, pubKey.value)
  params.passwordConfirm = FuncCrypt.rsaEncrypt(params.passwordConfirm, pubKey.value)
  params.old = FuncCrypt.rsaEncrypt(params.old, pubKey.value)
  AuthService.setPasswordChange(params).then((res: any) => {
    if (res.code == '000') {
      ElMessage({
        type: 'success',
        message: '修改密码成功'
      })
      setTimeout(() => {
        localStorage.removeItem('tokenAnc')
        globalStore.setLoginOut()
        if (import.meta.env.VITE_USER_NODE_ENV === 'development') {
          router.push('/login')
        } else {
          window.open(`${import.meta.env.VITE_BASE_URL}${import.meta.env.VITE_UNIVERSE_LOGIN}`, '_self')
        }
      }, 1500)
    } else {
      ElMessage({
        type: 'error',
        message: `${res.msg}`
      })
    }
  })
}
const _openDialog = () => {
  getPubKey()
  getVerifyCode()
}
// 退出登录
const setOut = () => {
  AuthService.setLogout().then((res: any) => {
    if (res.code == '000') {
      ElMessage({
        type: 'success',
        message: '退出登录成功'
      })
      setTimeout(() => {
        globalStore.setLoginOut()
        if (import.meta.env.VITE_USER_NODE_ENV === 'development') {
          router.push('/login')
        } else {
          window.open(`${import.meta.env.VITE_BASE_URL}${import.meta.env.VITE_UNIVERSE_LOGIN}`, '_self')
        }
      }, 1500)
    } else {
      ElMessage({
        type: 'error',
        message: `${res.msg}`
      })
    }
  })
}
// 获取可访问菜单
const getUserMenu = () => {
  MenuService.getUserMenu().then((res: any) => {
    menuList.value = res.result
  })
}
// 获取验证码
const getVerifyCode = () => {
  AuthService.getVerifyCode().then((res: any) => {
    let data = res.result as ApiAuth.ResVerifyCode
    imgVerifyCode.value = data.image
    form.value.picToken = data.token
    dialogFormVisible.value = true
  })
}

onMounted(() => {
  getUserMenu()
})
</script>

<style lang="scss" scoped>
.common-layout {
  width: 100%;
  height: 100%;
  background: url('@image/container/img_BG.jpg') no-repeat center / 100% 100%;
  .el-container {
    width: 100%;
    height: 100%;
  }
  .el-header {
    background-color: rgba(255, 255, 255, 0.6);
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header-left {
      display: flex;
      justify-items: center;
      .title {
        line-height: 30px;
        margin-left: 20px;
        font: 20px/20px AlibabaPuHuiTi-Bold;
        display: flex;
        align-items: center;
        font-weight: bold;
      }
    }
    .header-right {
      display: flex;
      align-items: center;
      .el-dropdown {
        cursor: pointer;
        margin-left: 10px;
      }
    }
  }
  .el-menu {
    background-color: rgba(255, 255, 255, 0.6);
    border-right: 0px;
  }
  .el-main {
    padding: 0px !important;
    display: flex;
    flex-direction: column;
    .main-btn {
      height: 40px;
      background-color: rgba(255, 255, 255, 0.6);
      display: flex;
      justify-content: space-between;
      padding: 0px 20px;
    }
    .main {
      padding: 20px;
      width: 100%;
      height: 100%;
    }
  }
  .el-form-item {
    margin-bottom: 20px;
  }

  .verify-code {
    height: 36px;
    cursor: pointer;
  }
}
</style>
